package com.hitqz.robot.biz.flow.component.agv;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotMapPos;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.driver.model.IRobotPosDto;
import com.hitqz.robot.driver.parent.RobotDriverService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2024/11/5
 */
@Slf4j
@LiteflowComponent(value = "PutWaitGoNextStep", name = "[轮对/轮轴]放--等待上位机可以执行下一步")
@AllArgsConstructor
public class PutWaitGoNextStep extends NodeComponent {

    private final RobotService robotService;

    private final RobotMapPosService robotMapPosService;

    private final RobotDriverService robotDriverService;

    @Override
    public void process() throws Exception {
        Robot robot = robotService.getDefaultRobot();
        FlowContextDto dto =  this.getRequestData();
        FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        IRobotPosDto iRobotPosDto = robotDriverService.getWebPos();
        RobotMapPos robotMapPos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                .eq(RobotMapPos::getCode, iRobotPosDto.getCurrentStation())
                .eq(RobotMapPos::getMapCode, robot.getMapCode()));
        log.info("直接到达位子：" + robotMapPos.getName());
        Cache<String, Boolean> nextStep = SpringUtil.getBean("nextStep");

        String targetName = ticketsDto.getModalData().get("targetPosName")== null ?
                String.valueOf(ticketsDto.getModalData().get("targetPosCode")):
                String.valueOf(ticketsDto.getModalData().get("targetPosName"));
        if (targetName.contains("LM")) {
            log.info("跳过等待");
            return;
        }
        while(true) {
            if (Boolean.TRUE.equals(nextStep.getIfPresent(robot.getRobotSn()))) {
                break;
            }
            nextStep = SpringUtil.getBean("nextStep");
            TimeUnit.SECONDS.sleep(1);
        }

        nextStep.put(robot.getRobotSn(), false);
    }
}
